#include "xdb_config.h"
#include "xdb_log.h"

#include <fstream>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <vector>

namespace xdragonball
{

int ConfigLoader(Config &cfg, const std::string &file)
{
	std::ifstream in(file.c_str());
	if (in.fail()) {
		return -1;
	}
	std::string line;
	while (std::getline(in, line)) {
		boost::algorithm::trim(line);
		if (line.size() == 0) {
			continue;
		}
		if (line[0] == '#') {
			continue;
		}
		int pos = line.find(':');
		if (pos < 0 || pos >= line.size()) {
			return -1;
		}
		std::string key = boost::algorithm::trim_copy(line.substr(0, pos));
		std::string val = boost::algorithm::trim_copy(line.substr(pos+1));
		cfg.get(key) = val;
		XDB_LOG_TRACE(line);
	}

	in.close();
	return 0;
}

Config & Config::get(const std::string &key, const char * flag) {
		std::vector<std::string> sp_vec;
		boost::algorithm::split(sp_vec, key, boost::is_any_of(flag));
		Config *ptr = this;
		for (int i=0; i<sp_vec.size(); ++i) {
			ptr = &(*ptr)[sp_vec[i]];
		}
		return *ptr;
}

const Config & Config::get (const std::string &key, const char *flag) const {
		std::vector<std::string> sp_vec;
		boost::algorithm::split(sp_vec, key, boost::is_any_of(flag));
		const Config *ptr = this;
		for (int i=0; i<sp_vec.size(); ++i) {
			ptr = &(*ptr)[sp_vec[i]];
		}
		return *ptr;
}


Config & Config::operator [] (const std::string &key) {
	if (_map == NULL) {
		_map = new std::map<std::string, Config *>;
	}
	Config *t = (*_map)[key];
	if (t == NULL) {
		t = new Config;
		(*_map)[key] = t;
	}

	return *t;
}

const Config & Config::operator [] (const std::string &key) const {
	static const Config CONFIG_DEF;
	if (_map) {
		std::map<std::string, Config *>::iterator iter = _map->find(key);
		if (iter == _map->end() || iter->second == NULL) {
			return CONFIG_DEF;
		}
		return *(iter->second);
	}
	return CONFIG_DEF;
}


};
